

#import "UIView+Extension.h"
#import <objc/runtime.h>

static char kDTActionHandlerTapBlockKey;
static char kDTActionHandlerTapGestureKey;
static char kDTActionHandlerLongPressBlockKey;
static char kDTActionHandlerLongPressGestureKey;

@interface UIView ()

@property(nonatomic,strong)UIActivityIndicatorView *activity;
@property(nonatomic,strong)UIImageView * bgViewDRDR;
@end

@implementation UIView (Extension)

+ (UIImage *)snapshotWithView:(UIView *)view {
    
    CGSize size = view.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)snapshotWithScrollView:(UIScrollView *)scrollView {
    
    UIImage *image = nil;
    UIGraphicsBeginImageContext(scrollView.contentSize);
    {
        CGPoint savedContentOffset = scrollView.contentOffset;
        CGRect savedFrame = scrollView.frame;
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    return image;
}

- (void)tap {
    NSLog(@"*****😁😁😁*****");
}
-(void)startLoading {
    if (!self.activity) {
        //
        if (!self.bgViewDRDR) {
            UIImageView * bgViewDRDRt = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            bgViewDRDRt.userInteractionEnabled = YES;
            [bgViewDRDRt addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]];
            self.bgViewDRDR = bgViewDRDRt;
            [self addSubview:self.bgViewDRDR];
        }
        //
        UIActivityIndicatorView *temp_activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        temp_activity.frame = CGRectMake(0, 0, 20, 20);
        temp_activity.center = CGPointMake(self.Sw/2, self.Sh/2);
        [temp_activity startAnimating];
        self.activity = temp_activity;
        [self addSubview:self.activity];
    }
}
-(void)stopLoding
{
    [self.bgViewDRDR removeFromSuperview];
    self.bgViewDRDR = nil;
    [self.activity stopAnimating];
    [self.activity removeFromSuperview];
    self.activity = nil;
}
// 在分类里添加属性
static char AddressKey;
static char BgViewKey;
-(void)setActivity:(UIActivityIndicatorView *)activity
{
    objc_setAssociatedObject(self, &AddressKey, activity, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}

-(UIActivityIndicatorView *)activity
{
    return objc_getAssociatedObject(self, &AddressKey);
}
- (void)setBgViewDRDR:(UIImageView *)bgViewDRDR {
    objc_setAssociatedObject(self, &BgViewKey, bgViewDRDR, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIImageView *)bgViewDRDR {
    return objc_getAssociatedObject(self, &BgViewKey);
}
-(void)addBorderWithcornerRad:(CGFloat)cornerRad lineCollor:(UIColor *)collor lineWidth:(CGFloat)lineWidth
{
    self.layer.borderWidth = lineWidth;
    self.cornerRad = cornerRad;
    self.layer.borderColor = collor.CGColor;
    
}

- (void)setTapActionWithBlock:(void (^)(void))block
{
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerTapGestureKey);
    
    if (!gesture)
    {
        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &kDTActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    
    objc_setAssociatedObject(self, &kDTActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)__handleActionForTapGesture:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        void(^action)(void) = objc_getAssociatedObject(self, &kDTActionHandlerTapBlockKey);
        
        if (action)
        {
            action();
        }
    }
}

- (void)setLongPressActionWithBlock:(void (^)(void))block
{
    UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerLongPressGestureKey);
    
    if (!gesture)
    {
        gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForLongPressGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &kDTActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    
    objc_setAssociatedObject(self, &kDTActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)__handleActionForLongPressGesture:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        void(^action)(void) = objc_getAssociatedObject(self, &kDTActionHandlerLongPressBlockKey);
        
        if (action)
        {
            action();
        }
    }
}

-(void)setCornerRad:(CGFloat)cornerRad
{
    self.layer.cornerRadius = cornerRad;
    self.layer.masksToBounds = YES;
    
}
-(CGFloat)cornerRad
{
    return self.cornerRad;
}
-(void)setCy:(CGFloat)Cy
{
    CGPoint center = self.center;
    center.y = Cy;
    self.center = center;
}
-(CGFloat)Cy
{
    return self.center.y;
}
-(void)setCx:(CGFloat)Cx
{
    CGPoint center = self.center;
    center.x = Cx;
    self.center = center;
}
-(CGFloat)Cx
{
    return self.center.x;
}
-(void)setSh:(CGFloat)Sh
{
    CGRect fram = self.frame;
    fram.size.height = Sh;
    self.frame = fram;
}
-(CGFloat)Sh
{
    return self.frame.size.height;
}
-(void)setSw:(CGFloat)Sw
{
    CGRect fram = self.frame;
    fram.size.width = Sw;
    self.frame = fram;
}
-(CGFloat)Sw
{
    return self.frame.size.width;
}

-(CGFloat)X
{
    return self.frame.origin.x;
}
-(CGFloat)Y
{
    return self.frame.origin.y;
}
-(void)setYs_x:(CGFloat)X
{
    CGRect frame = self.frame;
    frame.origin.x = X;
    self.frame = frame;
}
-(void)setYs_y:(CGFloat)Y
{
    CGRect frame = self.frame;
    frame.origin.y = Y;
    self.frame = frame;
}
- (void)setYs_size:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGSize)ys_size
{
    return self.frame.size;
}

-(void)setBlurStyle:(UIBlurEffectStyle)style
{
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:style];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = self.bounds;
    [self addSubview:effectView];
}
-(void)removeBlur
{
    for (UIView *temp_view in self.subviews) {
        
        if ([temp_view isKindOfClass:[UIVisualEffectView class]]) {
            
            [temp_view removeFromSuperview];
        }
    }
}

+(UIView *)CreateTableWithFrame:(CGRect )frame Number:(int)Number spacing:(CGFloat)spacing
{
    
    UIView *view = [[UIView alloc]initWithFrame:frame];
    
    
    CGRect rect = CGRectMake(0, 0, view.Sw/Number - spacing, view.Sh/Number - spacing);
    
    
    
    for (int i = 1 ; i <= Number; i++ ) {
        for (int j = 1; j <= Number; j++) {
            UIButton *button = [[UIButton alloc]initWithFrame:rect];
            [view addSubview:button];
            [button setBackgroundColor:[UIColor brownColor]];
            rect = CGRectOffset(rect, view.Sw/Number , 0);
            if (j == Number) {
                
                button.Sw += view.Sw - CGRectGetMaxX(button.frame);
            }
            
            if (i == Number) {
                
                button.Sh += view.Sh - CGRectGetMaxY(button.frame);
            }
        }
        
        rect.origin.x = 0;
        rect.origin.y = rect.origin.y + view.Sh/Number;
        
        
    }
    
    
    return view;
}
-(void)viewCutRoundedOfRectCorner:(UIRectCorner)rectCorner cornerRadii:(CGFloat)cornerRadii
{
    /*
     类型共有以下几种:
     
     * UIRectCornerTopLeft
     
     * UIRectCornerTopRight
     
     * UIRectCornerBottomLeft
     
     * UIRectCornerBottomRight
     
     * UIRectCornerAllCorners
     
     */
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(cornerRadii, cornerRadii)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    
    maskLayer.frame = self.bounds;
    
    maskLayer.path = maskPath.CGPath;
    
    self.layer.mask = maskLayer;
}
-(UIViewController*)MyViewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}


- (void)setViewBorderColor:(UIColor *)color border:(float)border type:(UIViewBorderLineType)borderLineType
{
    CALayer *lineLayer = [CALayer layer];
    lineLayer.backgroundColor = color.CGColor;
    switch (borderLineType) {
        case UIViewBorderLineTypeTop:{
            lineLayer.frame = CGRectMake(0, 0, self.frame.size.width, border);
            break;
        }
        case UIViewBorderLineTypeRight:{
            lineLayer.frame = CGRectMake(self.frame.size.width - border, 0, border, self.frame.size.height);
            break;
        }
        case UIViewBorderLineTypeBottom:{
            lineLayer.frame = CGRectMake(0, self.frame.size.height - border, self.frame.size.width,border);
            break;
        }
        case UIViewBorderLineTypeLeft:{
            lineLayer.frame = CGRectMake(0, 0, border, self.frame.size.height);
            break;
        }
            
        default:{
            lineLayer.frame = CGRectMake(0, 0, self.frame.size.width-42, border);
            break;
        }
    }
    
    [self.layer addSublayer:lineLayer];
    
}

- (void)setViewBorderColor:(UIColor *)color border:(float)border type:(UIViewBorderLineType)borderLineType begin:(float)begin end:(float)end
{
    CALayer *lineLayer = [CALayer layer];
    lineLayer.backgroundColor = color.CGColor;
    switch (borderLineType) {
        case UIViewBorderLineTypeTop:{
            lineLayer.frame = CGRectMake(begin, 0, self.frame.size.width - begin - end, border);
            break;
        }
        case UIViewBorderLineTypeRight:{
            lineLayer.frame = CGRectMake(self.frame.size.width - border, begin, border, self.frame.size.height - begin - end);
            break;
        }
        case UIViewBorderLineTypeBottom:{
            lineLayer.frame = CGRectMake(begin, self.frame.size.height - border, self.frame.size.width - begin - end,border);
            break;
        }
        case UIViewBorderLineTypeLeft:{
            lineLayer.frame = CGRectMake(0, begin, border, self.frame.size.height - begin - end);
            break;
        }
            
        default:{
            lineLayer.frame = CGRectMake(0, 0, self.frame.size.width, border);
            break;
        }
    }
    
    [self.layer addSublayer:lineLayer];
}


- (void)setViewBorderDottedLineColor:(UIColor *)color lineWidth:(float)lineWidth lineSpace:(float)lineSpace lineLength:(float)lineLength
{
    CAShapeLayer * lineLayer = [CAShapeLayer layer];
    lineLayer.strokeColor = color.CGColor;
    lineLayer.fillColor = nil;
    lineLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
    lineLayer.frame = self.bounds;
    lineLayer.lineWidth = lineWidth; // 线的宽度
    lineLayer.lineCap = @"square";
    lineLayer.lineDashPattern = @[[NSNumber numberWithFloat:lineSpace],[NSNumber numberWithFloat:lineLength]];
    [self.layer addSublayer:lineLayer];
    
}



- (void)setViewBorderDottedLineColor:(UIColor *)color lineWidth:(float)lineWidth lineSpace:(float)lineSpace lineLength:(float)lineLength type:(UIViewBorderLineType)borderLineType
{
    CAShapeLayer * lineLayer = [CAShapeLayer layer];
    lineLayer.strokeColor = color.CGColor;
    lineLayer.fillColor = nil;
    CGMutablePathRef path = CGPathCreateMutable();
    switch (borderLineType) {
        case UIViewBorderLineTypeTop:{
            CGPathMoveToPoint(path, NULL, lineWidth, lineWidth);  // y,x
            CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame),lineWidth); // h w
            break;
        }
        case UIViewBorderLineTypeRight:{
            CGPathMoveToPoint(path, NULL, CGRectGetWidth(self.frame) - lineWidth, lineWidth);
            CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame) - lineWidth,CGRectGetHeight(self.frame) - lineWidth);
            break;
        }
        case UIViewBorderLineTypeBottom:{
            CGPathMoveToPoint(path, NULL, lineWidth, CGRectGetHeight(self.frame) - lineWidth);
            CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame) - lineWidth,CGRectGetHeight(self.frame)- lineWidth);
            break;
        }
        case UIViewBorderLineTypeLeft:{
            CGPathMoveToPoint(path, NULL, lineWidth, lineWidth);
            CGPathAddLineToPoint(path, NULL, lineWidth,CGRectGetHeight(self.frame));
            break;
        }
            
        default:{
            break;
        }
    }
    lineLayer.path = path;
    lineLayer.frame = self.bounds;
    lineLayer.lineWidth = lineWidth; // 线的宽度
    lineLayer.lineCap = @"square";
    lineLayer.lineDashPattern = @[[NSNumber numberWithFloat:lineSpace],[NSNumber numberWithFloat:lineLength]];
    [self.layer addSublayer:lineLayer];
}


- (void)setViewBorderDottedLineColor:(UIColor *)color lineWidth:(float)lineWidth lineSpace:(float)lineSpace lineLength:(float)lineLength type:(UIViewBorderLineType)borderLineType begin:(float)begin end:(float)end
{
    CAShapeLayer * lineLayer = [CAShapeLayer layer];
    lineLayer.strokeColor = color.CGColor;
    lineLayer.fillColor = nil;
    CGMutablePathRef path = CGPathCreateMutable();
    switch (borderLineType) {
        case UIViewBorderLineTypeTop:{
            CGPathMoveToPoint(path, NULL, lineWidth + begin, lineWidth);  // y,x
            CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame) - end,lineWidth); // h w
            break;
        }
        case UIViewBorderLineTypeRight:{
            CGPathMoveToPoint(path, NULL, CGRectGetWidth(self.frame) - lineWidth, lineWidth + begin);
            CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame) - lineWidth,CGRectGetHeight(self.frame) - lineWidth - end);
            break;
        }
        case UIViewBorderLineTypeBottom:{
            CGPathMoveToPoint(path, NULL, lineWidth + begin, CGRectGetHeight(self.frame) - lineWidth);
            CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame) - lineWidth - end,CGRectGetHeight(self.frame) - lineWidth);
            break;
        }
        case UIViewBorderLineTypeLeft:{
            CGPathMoveToPoint(path, NULL, lineWidth, lineWidth  + begin);
            CGPathAddLineToPoint(path, NULL, lineWidth,CGRectGetHeight(self.frame) - end);
            break;
        }
            
        default:{
            break;
        }
    }
    lineLayer.path = path;
    lineLayer.frame = self.bounds;
    lineLayer.lineWidth = lineWidth; // 线的宽度
    lineLayer.lineCap = @"square";
    lineLayer.lineDashPattern = @[[NSNumber numberWithFloat:lineSpace],[NSNumber numberWithFloat:lineLength]];
    [self.layer addSublayer:lineLayer];
}



- (void)setViewBorderLine:(UIColor *)color frame:(CGRect)frame
{
    CALayer *lineLayer = [CALayer layer];
    lineLayer.backgroundColor = color.CGColor;
    lineLayer.frame = frame;
    [self.layer addSublayer:lineLayer];
}

- (void)setViewBorderColor:(UIColor *)color border:(float)border radius:(float)radius {
    //设置layer
    CALayer *layer= self.layer;
    //是否设置边框以及是否可见
    [layer setMasksToBounds:YES];
    //设置边框圆角的弧度
    [layer setCornerRadius:radius];
    //设置边框线的宽
    [layer setBorderWidth:border];
    //设置边框线的颜色
    [layer setBorderColor:[color CGColor]];
}

- (void)setViewCornerWithLeftTopCorner:(CGFloat)leftTop
                        rightTopCorner:(CGFloat)rigtTop
                      bottomLeftCorner:(CGFloat)bottemLeft
                     bottomRightCorner:(CGFloat)bottemRight {
    
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    
    UIBezierPath *maskPath = [UIBezierPath bezierPath];
    maskPath.lineWidth = 1.0;
    maskPath.lineCapStyle = kCGLineCapRound;
    maskPath.lineJoinStyle = kCGLineJoinRound;
    [maskPath moveToPoint:CGPointMake(bottemRight, height)]; //左下角
    [maskPath addLineToPoint:CGPointMake(width - bottemRight, height)];
    
    [maskPath addQuadCurveToPoint:CGPointMake(width, height- bottemRight) controlPoint:CGPointMake(width, height)]; //右下角的圆弧
    [maskPath addLineToPoint:CGPointMake(width, rigtTop)]; //右边直线
    
    [maskPath addQuadCurveToPoint:CGPointMake(width - rigtTop, 0) controlPoint:CGPointMake(width, 0)]; //右上角圆弧
    [maskPath addLineToPoint:CGPointMake(leftTop, 0)]; //顶部直线
    
    [maskPath addQuadCurveToPoint:CGPointMake(0, leftTop) controlPoint:CGPointMake(0, 0)]; //左上角圆弧
    [maskPath addLineToPoint:CGPointMake(0, height - bottemLeft)]; //左边直线
    [maskPath addQuadCurveToPoint:CGPointMake(bottemLeft, height) controlPoint:CGPointMake(0, height)]; //左下角圆弧

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)removeColorGradation {
    //   移除所有layer
      NSArray<CALayer *> *subLayers = self.layer.sublayers;
      NSArray<CALayer *> *removedLayers = [subLayers filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
          return [evaluatedObject isKindOfClass:[CAGradientLayer class]];
      }]];
      [removedLayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          [obj removeFromSuperlayer];
      }];
}

@end
